package openapi

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/oceanengine/ad_open_sdk_go/models"
	"google.golang.org/grpc/status"
	"io"
	"log"
	"net/http"
	"qm_system_server/server/global"
	"qm_system_server/server/model/common/response"
	"qm_system_server/server/proto/grpc/huge"
	"qm_system_server/server/proto/grpc/operate"
	"strconv"
	"strings"
)

type OpenApi struct {
}

func getToken() string {
	client := huge.NewHugeServiceClient(global.OperateGrpc)
	resp, err := client.GetAccessToken(context.Background(), &huge.TokenRequest{
		PlatformId: "1",
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			return st.Message()
		}
		return ""
	}
	return resp.AccessToken
}

func getHttp(params map[string]interface{}, apiUrl string, c *gin.Context) {
	accessToken := getToken()
	ctx := context.Background()

	_, httpResp, _ := global.GVA_OPEN_SDK.CommonApi().Get(ctx, apiUrl).
		AccessToken(accessToken).
		RequestQuery(params).Execute()

	var jsonData interface{}
	resBytes, _ := io.ReadAll(httpResp.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err := json.Unmarshal(resBytes, &jsonData)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	c.JSON(http.StatusOK, jsonData)
}

func postHttp(params map[string]interface{}, apiUrl string, c *gin.Context) {
	accessToken := getToken()
	ctx := context.Background()

	_, httpResp, _ := global.GVA_OPEN_SDK.CommonApi().Post(ctx, apiUrl).
		AccessToken(accessToken).
		RequestBody(params).Execute()

	var jsonData interface{}
	resBytes, _ := io.ReadAll(httpResp.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err := json.Unmarshal(resBytes, &jsonData)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	c.JSON(http.StatusOK, jsonData)
}

func (o *OpenApi) GetHugeData(c *gin.Context) {
	type request struct {
		// 请求参数
		GameHash   string `json:"game_hash" from:"game_hash"`
		Type       string `json:"type" form:"type"`
		StartDate  string `json:"start_date" form:"start_date"`
		EndDate    string `json:"end_date" form:"end_date"`
		PlatformId int64  `json:"platform_id" form:"platform_id"`
		Params     string `json:"params" form:"params"`
		Page       int64  `json:"page" form:"page"`
		Flag       int64  `json:"flag" form:"flag"`
		AddParams  string `json:"add_params" form:"add_params"`
	}

	var req request
	var platformId string

	c.ShouldBindQuery(&req)

	req.GameHash = c.Request.Header.Get("game-hash")

	if req.Flag == 0 {
		platformId = c.Request.Header.Get("platform-id")
		if platformId != "" {
			req.PlatformId, _ = strconv.ParseInt(platformId, 10, 64)
		}
	}

	grpcClient := operate.NewOperateServiceClient(global.OperateGrpc)

	resp, err := grpcClient.ShowData(context.Background(), &operate.ShowDataRequest{
		GameHash:   req.GameHash,
		Type:       req.Type,
		StartDate:  req.StartDate,
		EndDate:    req.EndDate,
		PlatformId: req.PlatformId,
		Params:     req.Params,
		Page:       req.Page,
		AddParams:  req.AddParams,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			// 获取 gRPC 错误的描述信息
			response.FailWithMessage(st.Message(), c)
		}
		return
	}

	response.OkWithData(response.PageResult{
		List:   resp.List,
		Total:  resp.Total,
		Page:   int(req.Page),
		Result: resp.Result,
	}, c)
}

func (o *OpenApi) GetDistrictList(c *gin.Context) {
	type GetDistrictListReq struct {
		AdvertiserId int64                              `json:"advertiser_id,omitempty" form:"advertiser_id"`
		Codes        string                             `json:"codes,omitempty" form:"codes"`
		Language     models.ToolsAdminInfoV2Language    `json:"language,omitempty" form:"language"`
		SubDistrict  models.ToolsAdminInfoV2SubDistrict `json:"sub_district,omitempty" form:"sub_district"`
	}

	var request GetDistrictListReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"codes":         request.Codes,
		"language":      request.Language,
		"sub_district":  request.SubDistrict,
	}
	getHttp(params, "/open_api/2/tools/admin/info/", c)
}

func (o *OpenApi) GetCustomCrowdList(c *gin.Context) {
	type GetCustomCrowdListReq struct {
		AdvertiserId int64 `json:"advertiser_id,omitempty" form:"advertiser_id"`
		SelectType   int64 `json:"select_type,omitempty" form:"select_type"`
		Offset       int64 `json:"offset,omitempty" form:"offset"`
		Limit        int64 `json:"limit,omitempty" form:"limit"`
	}
	var request GetCustomCrowdListReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"select_type":   request.SelectType,
		"offset":        request.Offset,
		"limit":         request.Limit,
	}
	getHttp(params, "/open_api/2/dmp/custom_audience/select/", c)

}

func (o *OpenApi) GetAwemeFanCategories(c *gin.Context) {
	type GetAwemeFanCategoriesReq struct {
		AdvertiserId int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		Behaviors    string `json:"behaviors,omitempty" form:"behaviors"`
	}

	var request GetAwemeFanCategoriesReq
	_ = c.ShouldBind(&request)
	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"behaviors":     request.Behaviors,
	}

	getHttp(params, "/open_api/2/tools/aweme_multi_level_category/get/", c)

}

func (o *OpenApi) GetAwemeAuthorInfo(c *gin.Context) {
	type GetAwemeAuthorInfoReq struct {
		AdvertiserId int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		LabelIds     string `json:"label_ids,omitempty" form:"label_ids"`
		Behaviors    string `json:"behaviors,omitempty" form:"behaviors"`
	}

	var request GetAwemeAuthorInfoReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"label_ids":     request.LabelIds,
		"behaviors":     request.Behaviors,
	}

	getHttp(params, "/open_api/2/tools/aweme_author_info/get/", c)

}

func (o *OpenApi) GetAwemeSearchInfo(c *gin.Context) {
	type GetAwemeSearchInfoReq struct {
		AdvertiserId int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		QueryWord    string `json:"query_word,omitempty" form:"query_word"`
		Behaviors    string `json:"behaviors,omitempty" form:"behaviors"`
	}

	var request GetAwemeSearchInfoReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"query_word":    request.QueryWord,
		"behaviors":     request.Behaviors,
	}

	getHttp(params, "/open_api/2/tools/aweme_info_search/", c)
}

func (o *OpenApi) GetAwemeFanAccounts(c *gin.Context) {
	type GetAwemeFanAccountsReq struct {
		AdvertiserId int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		CategoryId   string `json:"category_id,omitempty" form:"category_id"`
		Behaviors    string `json:"behaviors,omitempty" form:"behaviors"`
	}

	var request GetAwemeFanAccountsReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"category_id":   request.CategoryId,
		"behaviors":     request.Behaviors,
	}

	getHttp(params, "/open_api/2/tools/aweme_category_top_author/get/", c)
}

func (o *OpenApi) GetAwemeSimilarAccounts(c *gin.Context) {
	type GetAwemeSimilarAccountsReq struct {
		AdvertiserId int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		AwemeId      string `json:"aweme_id,omitempty" form:"aweme_id"`
		Behaviors    string `json:"behaviors,omitempty" form:"behaviors"`
	}

	var request GetAwemeSimilarAccountsReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"aweme_id":      request.AwemeId,
		"behaviors":     request.Behaviors,
	}

	getHttp(params, "/open_api/2/tools/aweme_similar_author_search/", c)
}

func (o *OpenApi) GetActionCategories(c *gin.Context) {
	type GetActionCategoriesReq struct {
		AdvertiserId int64 `json:"advertiser_id,omitempty" form:"advertiser_id"`
		ActionDays   int64 `json:"action_days,omitempty" form:"action_days"`
	}

	var request GetActionCategoriesReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"action_days":   request.ActionDays,
	}

	getHttp(params, "/open_api/2/tools/interest_action/action/category/", c)
}

func (o *OpenApi) GetInterestCategories(c *gin.Context) {
	type GetInterestCategoriesReq struct {
		AdvertiserId int64 `json:"advertiser_id,omitempty" form:"advertiser_id"`
	}

	var request GetInterestCategoriesReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
	}

	getHttp(params, "/open_api/2/tools/interest_action/interest/category/", c)
}

func (o *OpenApi) GetActionKeywords(c *gin.Context) {
	type GetActionKeywordsReq struct {
		AdvertiserId int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		QueryWords   string `json:"query_words,omitempty" form:"query_words"`
		ActionDays   int64  `json:"action_days,omitempty" form:"action_days"`
	}

	var request GetActionKeywordsReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"query_words":   request.QueryWords,
		"action_days":   request.ActionDays,
	}

	getHttp(params, "/open_api/2/tools/interest_action/action/keyword/", c)
}

func (o *OpenApi) GetInterestKeywords(c *gin.Context) {
	type GetInterestKeywordsReq struct {
		AdvertiserId int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		QueryWords   string `json:"query_words,omitempty" form:"query_words"`
	}

	var request GetInterestKeywordsReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"query_words":   request.QueryWords,
	}

	getHttp(params, "/open_api/2/tools/interest_action/interest/keyword/", c)
}

func (o *OpenApi) GetActionInterestKeywordSuggest(c *gin.Context) {
	type GetActionInterestKeywordSuggestReq struct {
		AdvertiserId  int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		Id            int64  `json:"id,omitempty" form:"id"`
		TagType       string `json:"tag_type,omitempty" form:"tag_type"`
		TargetingType string `json:"targeting_type,omitempty" form:"targeting_type"`
		ActionDays    int64  `json:"action_days,omitempty" form:"action_days"`
	}

	var request GetActionInterestKeywordSuggestReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id":  request.AdvertiserId,
		"id":             request.Id,
		"tag_type":       request.TagType,
		"targeting_type": request.TargetingType,
		"action_days":    request.ActionDays,
	}

	getHttp(params, "/open_api/2/tools/interest_action/keyword/suggest/", c)
}

func (o *OpenApi) GetInterestActionInfoByIs(c *gin.Context) {
	type GetInterestActionInfoByIsReq struct {
		AdvertiserId  int64  `json:"advertiser_id,omitempty" form:"advertiser_id"`
		Ids           string `json:"ids,omitempty" form:"ids"`
		TagType       string `json:"tag_type,omitempty" form:"tag_type"`
		TargetingType string `json:"targeting_type,omitempty" form:"targeting_type"`
		ActionDays    int64  `json:"action_days,omitempty" form:"action_days"`
	}

	var request GetInterestActionInfoByIsReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id":  request.AdvertiserId,
		"ids":            request.Ids,
		"tag_type":       request.TagType,
		"targeting_type": request.TargetingType,
		"action_days":    request.ActionDays,
	}

	getHttp(params, "/open_api/2/tools/interest_action/id2word/", c)
}

func (o *OpenApi) GetFlowPackage(c *gin.Context) {
	type GetFlowPackageReq struct {
		AdvertiserId int64 `json:"advertiser_id,omitempty" form:"advertiser_id"`
		Filering     struct {
			FlowPackageIds  string `json:"flow_package_ids,omitempty" form:"flow_package_ids"`
			FlowPackageType string `json:"flow_package_type,omitempty" form:"flow_package_type"`
		} `json:"filering,omitempty" form:"filering"`
		Page     int64 `json:"page,omitempty" form:"page"`
		PageSize int64 `json:"page_size,omitempty" form:"page_size"`
	}

	var request GetFlowPackageReq
	_ = c.ShouldBind(&request)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"filering": map[string]interface{}{
			"flow_package_ids":  request.Filering.FlowPackageIds,
			"flow_package_type": request.Filering.FlowPackageType,
		},
		"page":      request.Page,
		"page_size": request.PageSize,
	}

	getHttp(params, "/open_api/2/tools/union/flow_package/get/", c)
}

func (o *OpenApi) GetSuggestWords(c *gin.Context) {
	type GetSuggestWordsReq struct {
		AdvertiserId int    `json:"advertiser_id,omitempty" form:"advertiser_id"`
		Keyword      string `json:"keyword,omitempty" form:"keyword"`
	}
	var request GetSuggestWordsReq
	_ = c.ShouldBindJSON(&request)

	//字符串转int

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"query_list":    [1]string{request.Keyword},
	}

	postHttp(params, "/open_api/v3.0/sugg_words/", c)
}

type ApiOpenApiV30ProjectCreatePostRequest struct {
	ProjectCreateV30Request models.ProjectCreateV30Request `json:"ProjectCreateV30Request,omitempty"`
	MicroId                 string                         `json:"micro_id,omitempty"`
	PlatformId              string                         `json:"platform_id,omitempty"`
}

func (o *OpenApi) CreateProject(c *gin.Context) {
	var request ApiOpenApiV30ProjectCreatePostRequest

	_ = c.ShouldBindJSON(&request)

	ctx := context.Background()

	microIdNumber, _ := strconv.ParseInt(request.MicroId, 10, 64)
	request.ProjectCreateV30Request.MicroAppInstanceId = &microIdNumber

	accessToken := getToken()

	_, httpRes, _ := global.GVA_OPEN_SDK.ProjectCreateV30Api().
		Post(ctx).
		AccessToken(accessToken).
		ProjectCreateV30Request(request.ProjectCreateV30Request).
		Execute()

	type JsonData struct {
		Code    int    `json:"code"`
		Message string `json:"message"`
	}
	var resp JsonData
	resBytes, _ := io.ReadAll(httpRes.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err := json.Unmarshal(resBytes, &resp)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}

	if resp.Code != 0 {
		response.FailWithMessage(resp.Message, c)
		return
	}

	response.Ok(c)
}

type ApiOpenApiV30ProjectUpdatePostRequest struct {
	ProjectUpdateV30Request models.ProjectUpdateV30Request `json:"ProjectUpdateV30Request,omitempty"`
	ProjectId               string                         `json:"project_id,omitempty"`
}

func (o *OpenApi) UpdateProject(c *gin.Context) {
	var request ApiOpenApiV30ProjectUpdatePostRequest

	_ = c.ShouldBindJSON(&request)

	ctx := context.Background()

	accessToken := getToken()

	projectId, _ := strconv.ParseInt(request.ProjectId, 10, 64)
	request.ProjectUpdateV30Request.ProjectId = projectId

	_, httpRes, _ := global.GVA_OPEN_SDK.ProjectUpdateV30Api().
		Post(ctx).
		AccessToken(accessToken).
		ProjectUpdateV30Request(request.ProjectUpdateV30Request).
		Execute()

	type JsonData struct {
		Code    int    `json:"code"`
		Message string `json:"message"`
		Data    struct {
			ErrorList []struct {
				ErrorCode    int    `json:"error_code"`
				ErrorMessage string `json:"error_message"`
			} `json:"error_list"`
			ProjectId int `json:"project_id"`
		} `json:"data"`
	}
	var resp JsonData
	resBytes, _ := io.ReadAll(httpRes.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err := json.Unmarshal(resBytes, &resp)

	fmt.Println(resp)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	if resp.Code != 0 {
		response.FailWithMessage(resp.Message, c)
		return
	}

	if len(resp.Data.ErrorList) > 0 {
		response.FailWithMessage(resp.Data.ErrorList[0].ErrorMessage, c)
		return
	}

	response.Ok(c)
}

func (o *OpenApi) DelProject(c *gin.Context) {
	type DelProjectReq struct {
		AdvertiserId int    `json:"advertiser_id"`
		ProjectId    string `json:"project_id"`
	}

	var request DelProjectReq
	_ = c.ShouldBindJSON(&request)

	projectId, _ := strconv.Atoi(request.ProjectId)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"project_ids":   [1]int{projectId},
	}

	postHttp(params, "/open_api/v3.0/project/delete/", c)
}

func (o *OpenApi) UpdateStatusProject(c *gin.Context) {
	type UpdateStatusProjectReq struct {
		AdvertiserId int `json:"advertiser_id"`
		Data         struct {
			ProjectId string `json:"project_id"`
			OptStatus string `json:"opt_status"`
		} `json:"data"`
	}

	var request UpdateStatusProjectReq
	_ = c.ShouldBindJSON(&request)

	projectId, _ := strconv.Atoi(request.Data.ProjectId)

	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"data": [1]map[string]interface{}{
			{
				"project_id": projectId,
				"opt_status": request.Data.OptStatus,
			},
		},
	}

	fmt.Println(params)
	postHttp(params, "/open_api/v3.0/project/status/update/", c)
}

// 获取图片
func (o *OpenApi) GetImages(c *gin.Context) {
	type GetImagesReq struct {
		AdvertiserId int64                          `json:"advertiser_id" form:"advertiser_id"`
		Filtering    models.FileImageGetV2Filtering `json:"filtering,omitempty"  form:"filtering"`
		Page         int64                          `json:"page,omitempty"  form:"page"`
		PageSize     int64                          `json:"page_size,omitempty"  form:"page_size"`
		Ratio        string                         `json:"ratio,omitempty"  form:"ratio"`
		Width        int64                          `json:"width,omitempty" form:"width"`
		Height       int64                          `json:"height,omitempty" form:"height"`
		ImageIds     string                         `json:"image_ids,omitempty"  form:"image_ids"`
		MaterialIds  string                         `json:"material_ids,omitempty"  form:"material_ids"`
		Signatures   string                         `json:"signatures,omitempty"  form:"signatures"`
	}

	var request GetImagesReq
	_ = c.ShouldBind(&request)
	filtering := make(map[string]interface{})
	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"filtering":     request.Filtering,
		"page":          request.Page,
		"page_size":     request.PageSize,
	}
	if request.Ratio != "" {
		ratioStringArr := strings.Split(request.Ratio, ",")
		var ratioFloats []float64
		for _, part := range ratioStringArr {
			floatVal, _ := strconv.ParseFloat(part, 64)
			// 将转换后的float64值添加到切片中
			ratioFloats = append(ratioFloats, floatVal)
		}
		filtering["ratio"] = ratioFloats
	}

	if request.Width > 0 {
		filtering["width"] = request.Width
	}
	if request.Height > 0 {
		filtering["height"] = request.Height
	}
	if request.ImageIds != "" {
		imageIdArr := strings.Split(request.ImageIds, ",")
		filtering["image_ids"] = imageIdArr
	}
	if request.MaterialIds != "" {
		materialIdStringArr := strings.Split(request.MaterialIds, ",")
		var materialId []int64
		for _, part := range materialIdStringArr {
			intVal, _ := strconv.ParseInt(part, 10, 64)
			materialId = append(materialId, intVal)
		}
		filtering["material_ids"] = materialId
	}
	if request.Signatures != "" {
		signaturesArr := strings.Split(request.Signatures, ",")
		filtering["signatures"] = signaturesArr
	}

	if len(filtering) > 0 {
		params["filtering"] = filtering
	}

	getHttp(params, "/open_api/2/file/image/get/", c)
}

// 上传图片
func (o *OpenApi) UploadImage(c *gin.Context) {
	type UploadImageReq struct {
		AdvertiserId   string                         `form:"advertiser_id"`
		Filename       string                         `form:"filename"`
		ImageFile      models.FormFileInfo            `form:"image_file"`
		ImageSignature string                         `form:"image_signature"`
		ImageUrl       string                         `form:"image_url"`
		IsAigc         bool                           `form:"is_aigc"`
		UploadType     models.FileImageAdV2UploadType `form:"upload_type"`
	}
	var request UploadImageReq

	// 处理文件上传
	file, header, err := c.Request.FormFile("image_file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Error retrieving the file"})
		return
	}
	fileBytes, err := io.ReadAll(file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error reading the file"})
		return
	}

	imageFile := &models.FormFileInfo{
		FileName:  header.Filename,
		FileBytes: fileBytes,
	}

	hasher := md5.New()
	// 将字符串转换为字节数组，并写入哈希对象
	hasher.Write(fileBytes)
	// 计算哈希值，结果是一个字节数组
	hashBytes := hasher.Sum(nil)
	// 将字节数组转换为十六进制字符串
	imageSignature := hex.EncodeToString(hashBytes)

	advertiserId, _ := strconv.ParseInt(c.PostForm("advertiser_id"), 10, 64)
	uploadType := c.PostForm("upload_type")

	accessToken := getToken()
	ctx := context.Background()

	_, httpResp, _ := global.GVA_OPEN_SDK.FileImageAdV2Api().Post(ctx).
		AccessToken(accessToken).
		AdvertiserId(advertiserId).Filename(request.Filename).ImageFile(imageFile).ImageSignature(imageSignature).
		ImageUrl(request.ImageUrl).IsAigc(request.IsAigc).UploadType(models.FileImageAdV2UploadType(uploadType)).
		Execute()

	var jsonData interface{}
	resBytes, _ := io.ReadAll(httpResp.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err = json.Unmarshal(resBytes, &jsonData)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	c.JSON(http.StatusOK, jsonData)
}

// 获取视频
func (o *OpenApi) GetVideos(c *gin.Context) {
	type GetImagesReq struct {
		AdvertiserId int64                          `json:"advertiser_id" form:"advertiser_id"`
		Filtering    models.FileVideoGetV2Filtering `json:"filtering,omitempty"  form:"filtering"`
		Page         int64                          `json:"page,omitempty"  form:"page"`
		PageSize     int64                          `json:"page_size,omitempty"  form:"page_size"`
		VideoIds     string                         `json:"video_ids,omitempty"  form:"video_ids"`
		MaterialIds  string                         `json:"material_ids,omitempty"  form:"material_ids"`
		Signatures   string                         `json:"signatures,omitempty"  form:"signatures"`
		Source       string                         `json:"source,omitempty"  form:"source"`
		Width        int64                          `json:"width,omitempty" form:"width"`
		Height       int64                          `json:"height,omitempty" form:"height"`
		Ratio        string                         `json:"ratio,omitempty"  form:"ratio"`
	}
	var request GetImagesReq
	_ = c.ShouldBind(&request)
	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"filering": map[string]interface{}{
			"material_ids": request.Filtering.MaterialIds,
		},
		"page":      request.Page,
		"page_size": request.PageSize,
	}
	filtering := make(map[string]interface{})
	if request.VideoIds != "" {
		videoIdArr := strings.Split(request.VideoIds, ",")
		filtering["video_ids"] = videoIdArr
	}
	if request.MaterialIds != "" {
		materialIdStringArr := strings.Split(request.MaterialIds, ",")
		var materialId []int64
		for _, part := range materialIdStringArr {
			intVal, _ := strconv.ParseInt(part, 10, 64)
			materialId = append(materialId, intVal)
		}
		filtering["material_ids"] = materialId
	}
	if request.Signatures != "" {
		signaturesArr := strings.Split(request.Signatures, ",")
		filtering["signatures"] = signaturesArr
	}
	if request.Source != "" {
		sourceStringArr := strings.Split(request.Source, ",")
		filtering["source"] = sourceStringArr
	}
	if request.Ratio != "" {
		ratioStringArr := strings.Split(request.Ratio, ",")
		var ratioFloats []float64
		for _, part := range ratioStringArr {
			floatVal, _ := strconv.ParseFloat(part, 64)
			// 将转换后的float64值添加到切片中
			ratioFloats = append(ratioFloats, floatVal)
		}
		filtering["ratio"] = ratioFloats
	}
	if request.Width > 0 {
		filtering["width"] = request.Width
	}
	if request.Height > 0 {
		filtering["height"] = request.Height
	}
	if len(filtering) > 0 {
		params["filtering"] = filtering
	}
	getHttp(params, "/open_api/2/file/video/get/", c)
}

// 上传视频
func (o *OpenApi) UploadVideo(c *gin.Context) {
	type UploadVideoReq struct {
		AdvertiserId   string                         `form:"advertiser_id"`
		Filename       string                         `form:"filename"`
		VideoFile      models.FormFileInfo            `form:"video_file"`
		VideoSignature string                         `form:"video_signature"`
		VideoUrl       string                         `form:"video_url"`
		UploadType     models.FileVideoAdV2UploadType `form:"upload_type"`
	}

	var request UploadVideoReq
	// 处理文件上传
	file, header, err := c.Request.FormFile("video_file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Error retrieving the file"})
		return
	}
	fileBytes, err := io.ReadAll(file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error reading the file"})
		return
	}

	videoFile := &models.FormFileInfo{
		FileName:  header.Filename,
		FileBytes: fileBytes,
	}
	hasher := md5.New()
	// 将字符串转换为字节数组，并写入哈希对象
	hasher.Write(fileBytes)
	// 计算哈希值，结果是一个字节数组
	hashBytes := hasher.Sum(nil)
	// 将字节数组转换为十六进制字符串
	videoSignature := hex.EncodeToString(hashBytes)

	advertiserId, _ := strconv.ParseInt(c.PostForm("advertiser_id"), 10, 64)
	uploadType := c.PostForm("upload_type")

	accessToken := getToken()
	ctx := context.Background()

	_, httpResp, _ := global.GVA_OPEN_SDK.FileVideoAdV2Api().Post(ctx).
		AccessToken(accessToken).
		AdvertiserId(advertiserId).Filename(request.Filename).IsAigc(false).IsGuideVideo(false).
		UploadType(models.FileVideoAdV2UploadType(uploadType)).VideoFile(videoFile).VideoSignature(videoSignature).VideoUrl(request.VideoUrl).
		Execute()

	var jsonData interface{}
	resBytes, _ := io.ReadAll(httpResp.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err = json.Unmarshal(resBytes, &jsonData)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	c.JSON(http.StatusOK, jsonData)
}

// 获取音频
func (o *OpenApi) GetAudios(c *gin.Context) {
	type GetImagesReq struct {
		AdvertiserId int64                          `json:"advertiser_id" form:"advertiser_id"`
		Filtering    models.FileAudioGetV2Filtering `json:"filtering,omitempty"  form:"filtering"`
		Page         int64                          `json:"page,omitempty"  form:"page"`
		PageSize     int64                          `json:"page_size,omitempty"  form:"page_size"`
		AudioIds     string                         `json:"audio_ids,omitempty"  form:"audio_id"`
		MaterialIds  string                         `json:"material_ids,omitempty"  form:"material_ids"`
		Signatures   string                         `json:"signatures,omitempty"  form:"signatures"`
		Source       string                         `json:"source,omitempty"  form:"source"`
	}
	var request GetImagesReq
	_ = c.ShouldBind(&request)
	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"filering": map[string]interface{}{
			"material_ids": request.Filtering.MaterialIds,
		},
		"page":      request.Page,
		"page_size": request.PageSize,
	}
	filtering := make(map[string]interface{})
	if request.AudioIds != "" {
		audioIdArr := strings.Split(request.AudioIds, ",")
		filtering["audio_ids"] = audioIdArr
	}
	if request.MaterialIds != "" {
		materialIdStringArr := strings.Split(request.MaterialIds, ",")
		var materialId []int64
		for _, part := range materialIdStringArr {
			intVal, _ := strconv.ParseInt(part, 10, 64)
			materialId = append(materialId, intVal)
		}
		filtering["material_ids"] = materialId
	}
	if request.Signatures != "" {
		signaturesArr := strings.Split(request.Signatures, ",")
		filtering["signatures"] = signaturesArr
	}
	if request.Source != "" {
		sourceStringArr := strings.Split(request.Source, ",")
		filtering["source"] = sourceStringArr
	}
	if len(filtering) > 0 {
		params["filtering"] = filtering
	}
	getHttp(params, "/open_api/2/file/audio/get/", c)
}

// 上传音频
func (o *OpenApi) UploadAudio(c *gin.Context) {
	type UploadAudioReq struct {
		AdvertiserId   string                         `form:"advertiser_id"`
		AudioFile      models.FormFileInfo            `form:"audio_file"`
		AudioSignature string                         `form:"audio_signature"`
		AudioUrl       string                         `form:"audio_url"`
		UploadType     models.FileAudioAdV2UploadType `form:"upload_type"`
	}
	var request UploadAudioReq
	// 处理文件上传
	file, header, err := c.Request.FormFile("audio_file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Error retrieving the file"})
		return
	}
	fileBytes, err := io.ReadAll(file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error reading the file"})
		return
	}
	audioFile := &models.FormFileInfo{
		FileName:  header.Filename,
		FileBytes: fileBytes,
	}

	hasher := md5.New()
	// 将字符串转换为字节数组，并写入哈希对象
	hasher.Write(fileBytes)
	// 计算哈希值，结果是一个字节数组
	hashBytes := hasher.Sum(nil)
	// 将字节数组转换为十六进制字符串
	audioSignature := hex.EncodeToString(hashBytes)

	advertiserId, _ := strconv.ParseInt(c.PostForm("advertiser_id"), 10, 64)
	uploadType := c.PostForm("upload_type")

	accessToken := getToken()
	ctx := context.Background()

	_, httpResp, _ := global.GVA_OPEN_SDK.FileAudioAdV2Api().Post(ctx).
		AccessToken(accessToken).
		AdvertiserId(advertiserId).
		UploadType(models.FileAudioAdV2UploadType(uploadType)).AudioFile(audioFile).AudioSignature(audioSignature).AudioUrl(request.AudioUrl).
		Execute()

	var jsonData interface{}
	resBytes, _ := io.ReadAll(httpResp.Body)
	// 将 JSON 字符串解析为通用的 `interface{}`
	err = json.Unmarshal(resBytes, &jsonData)
	if err != nil {
		log.Fatalf("Error parsing JSON: %v", err)
	}
	c.JSON(http.StatusOK, jsonData)
}

// 获取图文素材
func (o *OpenApi) CarouselList(c *gin.Context) {
	type GetCarouseReq struct {
		AdvertiserId int64                          `json:"advertiser_id" form:"advertiser_id"`
		Filtering    models.CarouselListV2Filtering `json:"filtering,omitempty"  form:"filtering"`
		Page         int64                          `json:"page,omitempty"  form:"page"`
		PageSize     int64                          `json:"page_size,omitempty"  form:"page_size"`
		Source       string                         `json:"source,omitempty"  form:"source"`
		CarouselIds  string                         `json:"carousel_ids,omitempty"  form:"carousel_ids"`
		ImageIds     string                         `json:"image_ids,omitempty"  form:"image_ids"`
		AudioId      string                         `json:"audio_id,omitempty"  form:"audio_id"`
		FileName     string                         `json:"file_name,omitempty"  form:"file_name"`
	}
	var request GetCarouseReq
	_ = c.ShouldBind(&request)
	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"filering": map[string]interface{}{
			"carousel_ids": request.Filtering.CarouselIds,
		},
		"page":      request.Page,
		"page_size": request.PageSize,
	}
	filtering := make(map[string]interface{})
	if request.Source != "" {
		sourceStringArr := strings.Split(request.Source, ",")
		filtering["source"] = sourceStringArr
	}
	if request.ImageIds != "" {
		imageIdArr := strings.Split(request.ImageIds, ",")
		filtering["image_ids"] = imageIdArr
	}
	if request.CarouselIds != "" {
		CarouselIdArr := strings.Split(request.CarouselIds, ",")
		filtering["carousel_ids"] = CarouselIdArr
	}
	if request.AudioId != "" {
		filtering["audio_id"] = request.AudioId
	}
	if request.FileName != "" {
		filtering["file_name"] = request.FileName
	}
	if len(filtering) > 0 {
		params["filtering"] = filtering
	}
	getHttp(params, "/open_api/2/carousel/list/", c)
}

// 上传图文
func (o *OpenApi) CarouselCreate(c *gin.Context) {
	type CarouselCreateReq struct {
		AdvertiserId string                                      `json:"advertiser_id,omitempty" form:"advertiser_id"`
		AudioId      string                                      `json:"audio_id,omitempty"`
		Description  string                                      `json:"description,omitempty"`
		FileName     string                                      `json:"file_name,omitempty"`
		Images       []models.CarouselCreateV2RequestImagesInner `json:"images"`
	}
	var request CarouselCreateReq
	_ = c.ShouldBindJSON(&request)
	//字符串转int
	advertiserId, _ := strconv.Atoi(request.AdvertiserId)
	params := map[string]interface{}{
		"advertiser_id": advertiserId,
		"audio_id":      request.AudioId,
		"file_name":     request.FileName,
		"images":        request.Images,
	}
	postHttp(params, "/open_api/2/carousel/create/", c)
}

// 获取视频智能封面
func (o *OpenApi) VideoCoverSuggest(c *gin.Context) {
	type GetCarouseReq struct {
		AdvertiserId int64 `json:"advertiser_id" form:"advertiser_id"`
		VideoId      int64 `json:"video_id" form:"video_id"`
	}
	var request GetCarouseReq
	_ = c.ShouldBind(&request)
	params := map[string]interface{}{
		"advertiser_id": request.AdvertiserId,
		"video_id":      request.VideoId,
	}
	getHttp(params, "/open_api/tools/video_cover/suggest/", c)
}
